package servlets.loginServlets;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.User;


public class SocialLoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = -2636726244422059632L;
	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/LoginBySocial";


	
	
		protected void doGet(HttpServletRequest request, HttpServletResponse response){
			String id, social, answer;
			
			URL url;
			JsonManager jsonManager;
			User user = null;
			jsonManager = new JsonManager();
			id = request.getParameter("id");
			social = request.getParameter("social");
			
			try {
				url = new URL(URLBASE + "?id=" + id + "&social=" + social);
				answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
				
				
				if(answer.equals("null"))
					throw new Exception();
				
				
				user = jsonManager.toUser(answer);
				request.getSession().setAttribute("user", user);
				try {
					response.sendRedirect(request.getContextPath() + "/home.jsp");
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (Exception e1) {
				request.getSession().setAttribute("error", "yes");
				try {
					response.sendRedirect(request.getContextPath() + "/");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	
	
}
